<?php
namespace PFT\SMS;
use LaneWeChat\Core\Ext;
use LaneWeChat\Core\TemplateMessage;
include 'HongQunSms.class.php';
include 'TaoBaoSms.class.php';
if (!function_exists('ismobile')) {
    include '/var/www/html/new/d/common/func.inc.php';
}
define('LOG_NAME', '/var/www/html/new/d/logs/sms/order_sms_'.date('ymd').'.log');
if (!class_exists('Ext')) {
    if (empty($GLOBALS['aid']) && !defined('DEFAULT_WECHAT_APPID')) {
//        write_logs('aid 1='.$GLOBALS['aid'], '/var/www/html/wx/debug.txt');
        define('DEFAULT_WECHAT_APPID', 'wxd72be21f7455640d'); //票付通公众号
    }
//    write_logs('aid 2='.$GLOBALS['aid'], '/var/www/html/wx/debug.txt');

    //TODO::包含全局文件
    include '/var/www/html/wx/wechat/iwx.php';
}

/**
 * 【票付通】凭证号:{code}，您已成功购买了【{dname}】{pname}:{tnum}间，
 * 入住时间:{begintime}，离店时间:{endtime}，取票信息:{getaddr}，此为凭证，请妥善保管。
 * 详情及二维码:{link}
 */
class OrderSmsManual {
    private $order_tel;
    private $aid;
    private $fid;
    private $tid;
    private $pid;
    private $p_type;
    private $order_num;
    private $soap;
    private $db = null;
    private $source_apply_did;

    private $begin_time = null;
    private $end_time   = null;

    const SMS_FORMAT_STR  = 1;
    const SMS_FORMAT_ARR  = 2;


    const SMS_CONTENT_TPL = '入住凭证:{code}，您成功购买{pname}:{tnum}间，入住日期:{begintime}，离店日期:{endtime}。此为凭证，请妥善保管。详情及二维码:{link}';
    const SMS_CONTENT_TPL_GLY = '您已成功预订{pname}{tnum}间，凭证码：{code}.您可凭购票身份证、短信凭证码、二维码至厦门鼓浪屿漳州路3号皓月休闲度假俱乐部（皓月园内）办理入住，入住日期：{begintime}，离店日期：{endtime}。为方便您的游玩，建议您至少提前3天购买前往三丘田码头的船票,限取票当日使用，取后不退。祝您旅途愉快。详情及二维码：{link}';
    const SMS_CONTENT_TPL_H = '凭证号:{code},您已成功购买{begintime}{pname}:{tnum}张,{perinfo}{getaddr}。详情及二维码:{link}。';
    //【票付通】入住凭证：123456。您成功购买郁金香高级客房：3间，入住日期3月18日，离店日期3月22日。
//此为凭证，请妥善保管。详情及二维码:http://12301.cc/3u5235
//发给供应商的短信：

    public function __construct(\SoapClient $soap)
    {
        $this->soap = $soap;
        $this->db   = $this->db();
    }

    private function db()
    {
        $dsn = "mysql:dbname=myuu_test;host=127.0.0.1;port=3307";
        $pdo = new \PDO($dsn, 'wsdl', 'ws*753951');
        $pdo->exec('SET NAMES "UTF8"');
        return $pdo;
    }

    private function GetApplyDid($lid)
    {
        $sql = "SELECT apply_did,p_type FROM uu_land WHERE id=$lid LIMIT 1";
//        echo $sql, '<br>',PHP_EOL;
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        return $stmt->fetch(\PDO::FETCH_NUM);
    }
    public function GetPType()
    {
        return $this->p_type;
    }

    private function get_default_tpl($ptype)
    {
        $list = array(
            'DEFAULT' => '凭证号：{code}，您已成功购买了{pname}{tnum},消费日期：{begintime},{getaddr}，此为入园凭证,请妥善保管。详情及二维码:{link}',
            'C'       => self::SMS_CONTENT_TPL,
            'GLY'     => self::SMS_CONTENT_TPL_GLY,
        );
        return isset($list[$ptype]) ? $list[$ptype] : $list['DEFAULT'];
    }
    /**
     * 设置参数
     *
     * @param string $order_tel 客户手机号
     * @param int $aid 上级供应商id
     * @param int $fid 分销商id
     * @param int $tid 票id
     * @param int $pid 产品id
     * @param string $order_num 订单号
     * @param int $lid 景区id
     */
    public function SetParam($order_tel, $aid, $fid, $tid, $pid, $order_num, $lid)
    {
        $this->order_tel = (string)$order_tel;
        $this->aid = (int)$aid;
        $this->fid = (int)$fid;//$mainOrder['UUmid'];
        $this->tid = (int)$tid;//$mainOrder['UUtid'];
        $this->pid = (int)$pid;//$mainOrder['UUpid'];
        $this->order_num = (string)$order_num;//$mainOrder['UUordernum'];
        list($this->source_apply_did, $this->p_type) = $this->GetApplyDid((int)$lid);
//        print_r($ret);
//        echo $this->p_type = $ret['p_type'];
    }

    private function getCode()
    {
        $cert_xml = $this->soap->Terminal_Code_Verify( $this->order_num,1, 1);
        $cert_obj = simplexml_load_string($cert_xml);
        return (string)$cert_obj->Rec->UUcode;

    }

    private function SmsContent($p_name, $num, $begin_time, $end_time,
                                $ptype=null, $cformat='', $code=0,
                                $ret_format='string', $manualQr=false)
    {
//        凭证号:{code},您已成功购买了{pname}{tnum},消费日期:{begintime},{getaddr},此为入园凭证,请妥善保管。

        $search_replace = array();
        if ( $code>0 ) {
            $search_replace['{code}'] = (string)$code;
        } else {
            //获取凭证号
            $search_replace['{code}'] = $this->getCode();
        }
        $str="select dname from pft_member where id='$this->aid' LIMIT 1";
        $GLOBALS['le']->query($str);
        $GLOBALS['le']->fetch_assoc();
        $search_replace['{dname}'] = $GLOBALS['le']->f('dname');
        $search_replace['{pname}'] = $p_name;
        $search_replace['{tnum}']  = $num . ($this->p_type=='C' ? '' : '张');
        $search_replace['{begintime}']  = date('m月d日', strtotime($begin_time));
        $search_replace['{endtime}']    = date('m月d日', strtotime($end_time));

        $str="select getaddr from uu_jq_ticket where id='$this->tid' LIMIT 1";
        $stmt = $this->db->prepare($str);
        $stmt->execute();
        $search_replace['{getaddr}'] = $stmt->fetchColumn(0);


        //返回数组格式的数据
        if ($ret_format == self::SMS_FORMAT_ARR) {
            return $search_replace;
        }

        $sms_tpl = empty($cformat) ? $this->get_default_tpl($this->p_type) : $cformat;

        if (strpos($cformat, '{link}')!==false || strpos($sms_tpl, '{link}')!==false) {
            if ($manualQr) {
                $search_replace['{link}'] = "http://www.12301.cc/m_qr.html?$code";
            } else {
                $search_replace['{link}'] = "http://12301.cc/".url_sms($this->order_num);
            }
        }
//        if ($ptype=='H') {
//            $search_replace['{perinfo}'] = $perinfo;
//            $send_msg_word = str_replace(array_keys($search_replace),
//                array_values($search_replace), self::SMS_CONTENT_TPL_H);
//        }
//        else {
        //鼓浪屿休闲屋特殊处理
        if ($this->aid==24863) {
            $send_msg_word = str_replace(array_keys($search_replace),
                array_values($search_replace), self::SMS_CONTENT_TPL_GLY);
        }
        else {
            $send_msg_word = str_replace(array_keys($search_replace),
                array_values($search_replace), $sms_tpl);
        }
//        }

        $send_msg_word = trim($send_msg_word);
        $send_msg_word = str_replace(array(" ", "　"), array("", ""), $send_msg_word);
        return $send_msg_word;
    }


    /**
     * 即时通/鸿群发送短信
     *
     * @param $send_msg_world string 短信内容
     * @param int $sms_account 短信账号
     * @param int $dtype  短信渠道 0 即时通 1 鸿群 2 阿里大鱼
     * @param string $channel 发送渠道——限鸿群
     * @return bool
     */
    private function SendSms($send_msg_world, $sms_account=0, $dtype=0, $channel='')
    {
//        $send_msg_world = str_replace(array('[',']','【','】'), array('','','',''), $send_msg_world);
        if ($sms_account==0) {
            list($cformat, $dtype, $sms_account) = $this->GetSmsAccount($this->pid, $this->aid);
        }
        if ($dtype==0) {
            //使用集时通发送短信
            if (isset($sms_account) && $sms_account) $Taccount=$sms_account;
            else $Taccount='';
            $ret = $this->soap->reSend_SMS_Global_PL($this->order_num, $this->aid, $this->fid, $send_msg_world);
            $num = $this->soap->Send_SMS_V($this->order_tel, $send_msg_world, -1, $Taccount);
        } elseif ($dtype==1) {
            $channel = empty($channel) ? HongQunSms::KEY_MIX : HongQunSms::KEY_PFT;
            $num = HongQunSms::doSendSMS($this->order_tel, $send_msg_world, $channel);
        }
        write_logs($send_msg_world, LOG_NAME);
        $this->MoneyLog($num, $send_msg_world);
        return true;
    }

    /**
     * 记录发送日志，账户扣款
     *
     * @param $num  int 成功标识
     * @param $send_msg_world string 发送内容
     * @return int
     */
    private function MoneyLog($num, $send_msg_world)
    {
        return 100;
        //记录短信发送信息
        $times_num = ($num==100)?1:0;
        $str="select id from sms_order where ordernum='{$this->order_num}' limit 1";
        $stmt = $this->db->prepare($str);
        $stmt->execute();
        if ($stmt->fetchColumn(0)) {
            $str=<<<SQL
update sms_order set times=times+{$times_num},last_time=now(),
ordertel='{$this->order_tel}',smstxt='{$send_msg_world}',
fid={$this->fid},aid={$this->aid} where ordernum='{$this->order_num}' LIMIT 1
SQL;
        }
        else {
            $str=<<<SQL
insert sms_order set times=times+{$times_num},last_time=now(),
ordertel='{$this->order_tel}',smstxt='{$send_msg_world}',
fid={$this->fid},aid={$this->aid}
SQL;
        }
        $this->db->exec($str);

        $msgLen = str_len2($send_msg_world);
        $this->LogMoney($msgLen, $num);
        if ($num>0) {
            $str="update uu_ss_order set remsg=remsg+1 where ordernum='$this->order_num' limit 1";
            $this->db->exec($str);
            return 100;
        }else{
            $str="update uu_ss_order set smserror='$num' where ordernum='$this->order_num' limit 1";
            $this->db->exec($str);
            return $num;
        }
    }

    public function Send($p_name, $num, $begin_time, $end_time, $p_type='C', $code=0)
    {
        $p_type  = strtoupper($this->p_type);
        $sms_tpl = $this->SmsTemplate();

        if ($sms_tpl) {
            extract($sms_tpl);
        }
        //离店时间要加一天
        $end_time = date('Y-m-d', strtotime('+1 days', strtotime($end_time)));

        if ($sms_tpl['dtype']==2) {
            $sms_param = $this->SmsContent($p_name, $num, $begin_time,$end_time,
                $p_type, $sms_tpl['cformat'], $code, self::SMS_FORMAT_ARR);
            $result = TaoBaoSms::sendOrder($this->order_tel, $sms_tpl['sms_sign'],
                $sms_param['{code}'], $sms_param['{pname}'],$sms_param['{tnum}'],$sms_param['{begintime}'],
                $sms_param['{getaddr}'], $sms_param['{link}']);
//            var_dump($result);
            if($result!==0) {
                $this->MoneyLog($result['num'], $result['content']);
                return 100;
            }
            return 0;
        }
        else {
            $sms_content = $this->SmsContent($p_name, $num, $begin_time,
                $end_time, $p_type, $sms_tpl['cformat'],$code);
            if (!empty($sms_sign) ) {
                $sms_content = "【{$sms_sign}】$sms_content";
            }
        }

        //非酒店订单 设置了鸿群发送渠道 || $p_type=='C'
        if ( $sms_tpl['dtype']==1 ) {
            return $this->SendSms($sms_content, $sms_tpl['sms_account'], $sms_tpl['dtype']);
        }
        write_logs($sms_content.'---', LOG_NAME);
        $ret = $this->soap->reSend_SMS_Global_PL($this->order_num, $this->aid, $this->fid, $sms_content);
//        HongQunSms::Log("$this->order_num,$this->aid,$this->fid");
        return $ret;

//        $end_time = date('Y-m-d', strtotime('+1 days', strtotime($end_time)));
//        $sms_content = $this->SmsContent($p_name, $num, $begin_time, $end_time, $p_type);
//        return $this->SendSms($sms_content);
    }

    /**
     * 自定义凭证号短信
     *
     * @param $p_name
     * @param $num
     * @param $begin_time
     * @param $end_time
     * @param string $code  凭证号
     * @param bool $qrLink 是否显示自定义凭证号的二维码链接
     * @return mixed
     */
    public function SendWithVcode($p_name, $num, $begin_time, $end_time,
                                  $code, $qrLink=false)
    {
        $p_type  = strtoupper($this->p_type);
        $sms_tpl = $this->SmsTemplate();
        if ($sms_tpl) {
            extract($sms_tpl);
//            list($cformat, $dtype, $sms_account, $sms_sign) = array_values($sms_tpl);
        }
        //离店时间要加一天
        $end_time = date('Y-m-d', strtotime('+1 days', strtotime($end_time)));
        $sms_content = $this->SmsContent($p_name, $num, $begin_time, $end_time,
            $p_type, $cformat, $code, 'string', $qrLink);
        if (!empty($sms_sign) ) {
            $sms_content = "【{$sms_sign}】$sms_content";
        }
        return $this->soap->reSend_SMS_Global_PL($this->order_num, $this->aid, $this->fid, $sms_content);
//        return $this->SendSms($sms_content, $sms_account, $dtype, 'PFT_CHANNEL');
    }
    /**
     * 获取短信模板配置
     *
     * @return mixed
     */
    private function SmsTemplate()
    {
        $sql = <<<SQL
select cformat,dtype,sms_account,sms_sign from uu_sms_format where pid='{$this->pid}' limit 1
SQL;
        $GLOBALS['le']->query($sql);
        $row = $GLOBALS['le']->fetch_assoc();
        if (!$row) {
            $sql = <<<SQL
select cformat,dtype,sms_account,sms_sign from uu_sms_format where aid='{$this->aid}' and pid=0 ORDER BY id DESC limit 1
SQL;
            $GLOBALS['le']->query($sql);
            $row = $GLOBALS['le']->fetch_assoc();
        }
        return $row;
    }

    /**
     * 检查是否可以通过微信发送通知
     *
     * @param $fid 会员id
     * @param int $limit 是否限制查询条数，大于0表示限制返回条数
     * @return bool/string false/微信openid
     */
    public function WxNotifyChk($fid, $limit=0, $useOtherAppid=false)
    {
        $sql_openid = <<<SQL
SELECT fromusername,verifycode FROM uu_wx_member_pft WHERE fid=? AND tousername=?
 ORDER BY verifycode DESC
SQL;
        if ($limit) {
            $sql_openid .= " LIMIT $limit";
        }
        $stmt = $this->db->prepare($sql_openid);
        $appid = $useOtherAppid ? WECHAT_APPID : Ext::PFT_APP_ID;
        $stmt->execute(array($fid, $appid));
//        if ($_GET['test']) {
//            print_r(array($fid, Ext::PFT_APP_ID));
//        }
        $tmp    = array();
        $openid = array();
        while($row=$stmt->fetch(\PDO::FETCH_ASSOC)) {
            if ($row['verifycode']==1) {
                $openid[] = $row['fromusername'];
            }
            $tmp[] = $row['fromusername'];
        }
        $cnt = count($openid);
        if (($cnt==1||$cnt==0) && count($tmp)) {
            //如果都没有设置的话，那么随机选择一个
            return array_shift($tmp);
        }
        elseif(count($openid)) {
            return $openid;
        }
        return false;

    }

    /**
     * 微信通知下单的人
     *
     * @param string $wx_open_id
     * @param string $time
     * @param string $name
     * @param string $itemName
     * @param string $itemData
     * @param string $ordernum
     */
    public function WxNotifyCustomer($wx_open_id, $time, $name,
                                     $itemName, $itemData, $ordernum,$totalPay=0)
    {
        switch ($this->p_type) {
            case 'A':
                $type = '门票订单';
                break;
            case 'B':
                $type = '线路订单';
                break;
            case 'C':
                $type = '酒店订单';
                break;
            case 'F':
                $type = '套票订单';
                break;
            case 'G':
                $type = '餐饮订单';
                break;
            default:
                $type = '门票订单';
                break;
        }
        $remark = ($totalPay>0? "消费金额：$totalPay 元\n" :'') . "订单号：{$ordernum}" ;
        $data = array(
            'first' => array('value' => '订单提交成功', 'color' => '#173177'),
            'tradeDateTime' => array('value' => $time, 'color' => '#173177'),
            'orderType' => array('value' => $type, 'color' => '#ff9900'),
            'customerInfo' => array('value' => $name, 'color' => '#173177'),
            'orderItemName' => array('value' => $itemName, 'color' => '#173177'),
            'orderItemData' => array('value' => $itemData, 'color' => '#173177'),
            'remark' => array('value' => $remark, 'color' => ''),
        );
//        Ext::Log(json_encode($data),'APPID='.WECHAT_APPID, '/var/www/html/wx/debug.txt');
//        write_logs(json_encode($data),'APPID='.WECHAT_APPID,'/var/www/html/wx/debug.txt');

        $tplId = TemplateMessage::getTmpId('NEW_ORDER');
        return TemplateMessage::sendTemplateMessage($data,
            $wx_open_id, $tplId,
            "http://503334.12301.cc/wx/html/order_detail.html?fromt=f542e9fac6e76f4b3b66422d49e5585c&ordernum=$ordernum",
            '#FF0000');
    }

    /**
     * @param string $wx_open_id openid
     * @param string $order_num 订单号
     * @param string $p_name 产品名称
     * @param string $remark 文字说明
     * @param string $pid 产品编号
     */
    public function WxNotifyProvider($wx_open_id, $order_num, $p_name, $remark, $pid = '')
    {
//        {{first.DATA}}
//        订单号：{{OrderId.DATA}}
//        产品编号：{{ProductId.DATA}}
//        产品名称：{{ProductName.DATA}}
//        {{remark.DATA}}
//        您好！您有新订单：
        //2015年5月30日 22:02:13,更新：通知供应商只能通过票付通公众号来通知。
        //还不知道有什么问题
//        define('DEFAULT_WECHAT_APPID', 'wxd72be21f7455640d'); //票付通公众号
        include '/var/www/html/wx/wechat/lanewechat.php';
        $data = array(
            'first' => array('value' => '您好！您有新订单：', 'color' => '#173177'),
            'OrderId' => array('value' => $order_num, 'color' => '#173177'),
            'ProductId' => array('value' => $pid, 'color' => '#ff9900'),
            'ProductName' => array('value' => $p_name, 'color' => '#173177'),
            'remark' => array('value' => $remark, 'color' => ''),
        );
        $ret = TemplateMessage::sendTemplateMessage($data,
            $wx_open_id, TemplateMessage::HOTEL_ORDER_MSG,
            "http://wx.12301.cc/html/order_detail.html?fromt=f542e9fac6e76f4b3b66422d49e5585c&ordernum=$order_num",
            '#FF0000');
//        if ($_GET['test']) {
//            print_r($data);
//            print_r($ret);
//            print_r($wx_open_id);
//        }
    }

    /**
     * 酒店订单通知供应商
     *
     * @param string $dname 顾客姓名
     * @param string $pname 产品名称
     * @param int $num 预定间数
     * @param string $begintime 入住时间
     * @param string $endtime 离店时间
     * @param string $order_num 订单号
     * @param string $memo 备注信息
     * @return bool
     */
    public function SmsToApplyErHotel($dname, $pname, $num, $begintime,
                                      $endtime, $order_num, $memo)
    {
        if (!$memo ) $memo = '无';
        if (!is_null($this->begin_time)) {
            $begintime = $this->begin_time;
        }

        if (!is_null($this->end_time)) {
            $endtime = $this->end_time;
        }

        $begintime  = date('m月d日', strtotime($begintime));
        $endtime    = date('m月d日', strtotime('+1 days', strtotime($endtime)));

        $wx_remark = "预定人：{$dname}\n房间数：{$num}\n"
            . "入住时间：$begintime\n离店时间：$endtime\n"
            . "订单备注：{$memo}\n\n为了客人出行，请尽快确认，谢谢！";
        //先用微信通知
        if ($wx_open_id = $this->WxNotifyChk($this->source_apply_did)) {
            if (is_array($wx_open_id)) {
                foreach ($wx_open_id as $openid) {
                    $this->WxNotifyProvider($openid, $order_num, $pname, $wx_remark);
                }
            }
            else {
                $this->WxNotifyProvider($wx_open_id, $order_num, $pname, $wx_remark);
            }
        }
        //查看哪些产品需要发送短信给供应商
        $sql = <<<SQL
SELECT f.pid,f.confirm_sms,l.fax,l.apply_did FROM uu_land_f f
LEFT JOIN uu_land l ON l.id=f.lid
WHERE f.pid=$this->pid LIMIT 1
SQL;
//        echo $sql;
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
        if ($row['confirm_sms']!=1 || $row['confirm_sms']!=3 || !$row['fax']) {
            return false;
        }

        $tpl    = file_get_contents('/var/www/html/new/d/tpl/sms/hotel_order.txt');
//预订通知：客人{dname}预订了{pname}{num}间，{begintime}入住，
//        {endtime}离店，订单号：{ordernum}。联系电话：{tel}。
//        客人备注信息：{note}。【票付通】
        $search = array(
            '{dname}',
            '{pname}',
            '{num}',
            '{begintime}',
            '{endtime}',
            '{ordernum}',
            '{tel}',
            '{note}',
        );
//        $search_replace['{begintime}']  = date('m月d日', strtotime($begin_time));
//        $search_replace['{endtime}']    = date('m月d日', strtotime($end_time));
        //UUmemo
        $replace_arr = array(
            $dname,
            $pname,
            $num,
            $begintime,
            $endtime,
            $order_num,
            $this->order_tel,
            $memo,
        );
        $smsTxt = str_replace($search, $replace_arr, $tpl);
//        echo $smsTxt;
        $num    = $this->soap->Send_SMS_V($row['fax'], $smsTxt);
        $msgLen = str_len2($smsTxt);
        $this->LogMoney($msgLen, $num);
    }

    /**
     * 非酒店订单发送短信/微信通知供应商
     *
     * @param string $data_type 数据类型:AFTER_SUBMIT标识下单后发送【$data为产品信息】，AFTER_PAY标识支付后发送【$data为订单信息】
     * @param array $data 产品数据或订单数据
     * @param string $customer_name 下单人姓名
     * @param string $order_num 订单号
     * @param string $tel 联系电话
     * @param null $note 备注信息
     * @return bool
     */
    public function OrderNotify($data_type, Array $data, $customer_name = '',
                                $order_num = '', $tel = '', $note = null)
    {
//        write_logs('供应商短信通知', LOG_NAME);
        $order_content = $land_title = '';
        $pids = array();
        //提交订单后发生通知短信
        if ($data_type == 'AFTER_SUBMIT') {
            foreach ($data as $prod) {
                $pids[] = $prod['pid'];
                $land_title = $prod['ltitle'];
                $order_content .= "{$prod['ttitle']}{$prod['tnum']}张;";
            }
        }
        elseif ($data_type == 'AFTER_PAY') {
            $this->pid = (string)$data['mainOrder']->UUpid;
            if (!$order_num) {
                $this->order_num = (string)$data['mainOrder']->UUordernum;
                $order_num = $this->order_num;
            }
            if ($data['mainOrder']->UUaids==0) {
                $this->source_apply_did = (int)$data['mainOrder']->UUaid;
            } elseif (strpos($data['mainOrder']->UUaids,',')!==false) {
                $this->source_apply_did = array_shift(
                    explode(',', (string)$data['mainOrder']->UUaids)
                );
            }

            //订单支付后发送短信
            $land_title = strval($data['mainOrder']->UUltitle);
            $pids[] = (int)$data['mainOrder']->UUpid;
            $order_content .= "{$data['mainOrder']->UUttitle}{$data['mainOrder']->UUtnum}张;";
            $customer_name = strval($data['mainOrder']->UUordername);
            $note = strval($data['mainOrder']->UUmemo);
            $tel = strval($data['mainOrder']->UUordertel);
            if (count($data['childOrder']) > 0) {
                foreach ($data['childOrder'] as $child) {
                    $pids[] = (int)$child->UUpid;
                    $order_content .= "{$child->UUttitle}{$child->UUtnum}张;";
                }
            }
        }
//        if ($_GET['test']) {
//            echo $order_content;
//            exit;
//        }
//        write_logs('供应商短信通知', LOG_NAME);
        return $this->SmsToProvider($pids, $customer_name,
            $land_title, $order_content, $order_num, $tel, $note);
    }

    /**
     * 向供应商发送通知信息
     *
     * @param array $pids 预定的产品id
     * @param string $customer_name 下单人姓名
     * @param string $land_title 产品名称
     * @param string $order_content 购买的产品
     * @param string $order_num 订单号
     * @param string $tel 联系电话
     * @param string $note 备注信息
     * @return bool
     */
    private function SmsToProvider($pids, $customer_name, $land_title, $order_content,
                                   $order_num, $tel, $note)
    {
        //查看哪些产品需要发送短信给供应商
        $apply_did = $this->source_apply_did;
        $sms_account = array(7517=>'glyylq',24863=>'glyylq');
        $sql = "SELECT f.pid,f.confirm_sms,f.confirm_wx,l.fax FROM uu_land_f f"
            . " LEFT JOIN uu_land l ON l.id=f.lid WHERE f.pid IN("
            . implode(',', $pids) . ") LIMIT " . count($pids);
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        $sms_notify_num = null;
        $confirm_wx = 0;//接收微信通知标记
        while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
//            $apply_did = $row['apply_did'];
            if ($row['confirm_wx']) {
                $confirm_wx = 1;
            }
            if (($row['confirm_sms'] == 1 || $row['confirm_sms']==3 ) && $row['fax']) {
                $sms_notify_num = $row['fax'];
                break;
            }
        }

        if (!class_exists('Log')) {
            include_once 'Log.class.php';
        }
//        $logTime = date('Y-m-d H:i:s');
        $sms_tpl = '预订通知：客人{dname}预订了{product_content}，订单号：{ordernum}。联系电话：{tel}。';

        if ($note) {
            $sms_tpl .= "客人备注信息：{$note}。";
        }
        //微信通知
        if ($confirm_wx && ($wx_open_id = $this->WxNotifyChk($apply_did)) ) {
            //如果绑定了多个微信号
            if (is_array($wx_open_id)) {
                foreach ($wx_open_id as $openid) {
                    $this->WxNotifyProvider(
                        $openid,
                        $order_num,
                        $land_title,
                        $order_content,
                        $this->pid
                    );
                }
            }
            else {
                $this->WxNotifyProvider(
                    $wx_open_id,
                    $order_num,
                    $land_title,
                    $order_content,
                    $this->pid
                );
            }
        }
        //短信通知

        if (!is_null($sms_notify_num) && ismobile($sms_notify_num)) {
            $sms_word = str_replace(
                array('{dname}', '{product_content}', '{ordernum}', '{tel}'),
                array($customer_name, $land_title . $order_content, $order_num, $tel),
                $sms_tpl
            );
            write_logs("sms_account={$sms_account[$apply_did]}|sms_word=$sms_word|mobile=$sms_notify_num", LOG_NAME);
            $ret = $this->soap->Send_SMS_V($sms_notify_num, $sms_word,'', $sms_account[$apply_did]);
            //短信扣费
            $this->LogMoney(str_len2($sms_word), $ret);
        }
        return true;
    }

    /**
     * 发送通知
     *
     * @param array $order 订单数据，根据DisOrder::orer
     * @param bool $send2ApplyEr
     * @param bool $useWxNotify
     * @return int
     */
    public function SendByOrderInfo(Array $order, $send2ApplyEr = true, $useWxNotify = true)
    {
        $this->SetParam(
            $order['mainOrder']->UUordertel,
            $order['mainOrder']->UUaid,
            $order['mainOrder']->UUmid,
            $order['mainOrder']->UUtid,
            $order['mainOrder']->UUpid,
            $order['mainOrder']->UUordernum,
            $order['mainOrder']->UUlid
        );
        if ($useWxNotify && $wx_open_id = $this->WxNotifyChk($order['mainOrder']->UUmid, 1)) {
            $unit = $this->p_type == 'C' ? '间' : '张';
            $itemData = "{$order['mainOrder']->UUttitle}:{$order['mainOrder']->UUtnum} $unit；";
            if (count($order['childOrder']) > 0) {
                foreach ($order['childOrder'] as $child) {
                    $itemData .= "\n$child->UUttitle:$child->UUtnum $unit；";
                }
            }
            $this->WxNotifyCustomer($wx_open_id,
                (string)$order['mainOrder']->UUordertime,
                (string)$order['mainOrder']->UUordername,
                (string)$order['mainOrder']->UUltitle,
                $itemData,
                $order['mainOrder']->UUordernum
            );
        }

        //判断是否需要发送凭证码
        $sql_chk_notify = "SELECT sendVoucher from uu_land_f WHERE pid=? LIMIT 1";
        $stmt = $this->db->prepare($sql_chk_notify);
        $stmt->execute(array($this->pid));
        if ($stmt->fetchColumn(0)==1) {
            return '该票类设置了不发送凭证码，发送失败';
        }
        //短信发送次数超过3次的不发送
        if ($order['mainOrder']->UUremsg>3) {
            return 116;
        }
        $p_name  = strval($order['mainOrder']->UUltitle . $order['mainOrder']->UUttitle);

        //非酒店类型的订单
        if ($this->p_type != 'C') {
            if ($send2ApplyEr) {
                $this->OrderNotify('AFTER_PAY', $order);
            }
//            return $this->Send($p_name, intval($order['mainOrder']->UUtnum),
//                (string)$order['mainOrder']->UUbegintime, $this->end_time);
            return $this->soap->reSend_SMS_Global_PL($this->order_num,
                $this->aid,$this->fid);//重发短信
        }
        $time_list = array((string)$order['mainOrder']->UUbegintime);
        if (count($order['childOrder'])>0) {
            foreach ($order['childOrder'] as $child) {
                $time_list[] = (string)$child->UUbegintime;
            }
        }
        else {
            $time_list[] = (string)$order['mainOrder']->UUbegintime;
        }

        sort($time_list);

        $this->begin_time = array_shift($time_list);
        $this->end_time   = array_pop($time_list);

        if ($send2ApplyEr) {
            $this->SmsToApplyErHotel(
                (string)$order['mainOrder']->UUordername,
                $p_name,
                intval($order['mainOrder']->UUtnum),
                $this->begin_time,
                $this->end_time,
                $this->order_num,
                (string)$order['mainOrder']->UUmemo
            );
        }
        return $this->Send($p_name, intval($order['mainOrder']->UUtnum),
            $this->begin_time, $this->end_time, 'C');
    }

    private function GetSmsAccount()
    {
        $str="select cformat,dtype,sms_account from uu_sms_format"
            ." where pid='{$this->pid}' or aid='{$this->source_apply_did}'"
            ." order by aid desc limit 1";
        $stmt = $this->db->prepare($str);
        $stmt->execute();
        return $stmt->fetch(\PDO::FETCH_NUM);
    }

    private function LogMoney($msg_len, $num)
    {
        //扣除短信费用
        if ($num==100){
            $m = ceil($msg_len / 66);
            $str="select fee_sms,fee_pay_way from pft_member where id=? limit 1";
//            echo $str,'<br/>',PHP_EOL;
            $stmt = $this->db->prepare($str);
            $stmt->execute(array($this->source_apply_did));
            $FeeConf = $stmt->fetch(\PDO::FETCH_ASSOC);

            $fee_sms=$FeeConf['fee_sms'];
            $fee_pay_way=$FeeConf['fee_pay_way'];
            $dmoney=$fee_sms*$m;

            $fee_member=($fee_pay_way==1)? $this->fid : $this->source_apply_did;

            $str="update pft_member_money set amoney=amoney-$dmoney where fid=$fee_member LIMIT 1";
//            echo $str,'<br/>',PHP_EOL;
            $this->db->exec($str);

            $str="select amoney from pft_member_money where fid=$fee_member limit 1";
//            echo $str,'<br/>',PHP_EOL;
            $stmt = $this->db->prepare($str);
            $stmt->execute();
            $lmoney=$stmt->fetchColumn(0);

            $str="insert pft_member_journal set fid=$fee_member,dmoney=$dmoney,lmoney=$lmoney,orderid='$this->order_num',daction=1,rectime=now(),dtype=8,ptype=0";
//            echo $str,'<br/>',PHP_EOL;
            $this->db->exec($str);

            //平台流水帐
            $str="update pft_member_money set amoney=amoney+$dmoney where fid=1 LIMIT 1";
//            echo $str,'<br/>',PHP_EOL;
            $this->db->exec($str);
            $str="select amoney from pft_member_money where fid=1 limit 1";
//            echo $str,'<br/>',PHP_EOL;
            $stmt = $this->db->prepare($str);
            $stmt->execute();
            $lmoney=$stmt->fetchColumn(0);
            $str="insert pft_member_journal set fid=1,dmoney=$dmoney,lmoney=$lmoney,orderid='$this->order_num',daction=0,rectime=now(),dtype=8,ptype=0";
//            echo $str,'<br/>',PHP_EOL;
            $this->db->exec($str);

            return true;
        }
        return false;
    }
}

#EOF CLASS

function url_sms($n)
{
    $na=array("u","l","5","4","3","2","1","y","s","t");
    $n=(string)$n;
    $s="";
    $len=strlen($n);
    for ($i=0;$i<$len;$i++){
        $s.=$na[$n{$i}];
    }
    return $s;
}

if (!function_exists('str_len2')) {
    function str_len2($str)
    {
        $length = strlen(preg_replace('/[\x00-\x7F]/', '', $str));

        if ($length)
        {
            return strlen($str) - $length + intval($length / 3);
        }
        else
        {
            return strlen($str);
        }
    }
}